// web/src/app/api/(social)/conversations/route.ts

import {NextRequest, NextResponse} from "next/server";
import {db} from "@/lib/db";

export async function GET(req: NextRequest) {
    try {
        const searchParams = req.nextUrl.searchParams;
        let workspaceId = (searchParams.get('workspaceId'))!
        let memberOneId = (searchParams.get('memberOneId'))!
        let memberTwoId = (searchParams.get('memberTwoId'))!

        let where = {
            workspaceId, memberOneId, memberTwoId
        }
        const conversations = await db.conversation.findMany({
            where
        })

        return NextResponse.json(conversations)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}

export async function POST(req: NextRequest) {
    try {
        let values = await req.json()
        console.log('create conversation', values)

        if (await db.conversation.findFirst({
            where: values
        }))
            return new NextResponse('Conversation existed!', {status: 400})

        const conversation = await db.conversation.create({
            data: values
        })

        return NextResponse.json(conversation)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}